<template>
	<view class="pay">
		<u-popup
			mode="bottom"
			closeable
			:show="showPay"
			@close="closePay">
			<view class="pay-popup">
				<view class="pay-popup-title main-flex">订单支付</view>
				<view class="pay-popup-content">
					<view class="pay-popup-money">
						<text class="pay-popup-money-unit">￥</text>
						<text class="pay-popup-money-num">{{order?.actualPrice?moneyStr(order?.actualPrice):'0.00'}}</text>
					</view>
					<view class="pay-popup-way">
						<u-radio-group
							v-model="payWayId"
							placement="column">
							<view class="pay-popup-way-item main-flex" v-for="item in payWayList" :key="item.id">
								<view class="pay-popup-way-item-icon">
									<image class="pay-popup-way-item-icon-img" mode="aspectFit" :src="imgUrl(item.img)"></image>
								</view>
								<view class="pay-popup-way-item-name">{{item.name}}</view>
								<view class="pay-popup-way-item-check" @click="changePayWay(item)">
									<uni-icons v-if="payWayId == item.id" type="checkbox-filled" size="30" color="#e3230e"></uni-icons>
									<uni-icons v-else type="circle" size="30" color="#d1d1d1"></uni-icons>
								</view>
								<view class="pay-popup-way-item-no">
									<u-radio :label="item.name" :name="item.id">
									</u-radio>
								</view>
							</view>
						</u-radio-group>
					</view>
				</view>
				<view class="pay-popup-btns main-flex">
					<button :disabled="isSubmitPay" :loading="isSubmitPay" class="ty-button ty-button-confirm pay-popup-btns-item" @click="submitPay">确认支付</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup>
  import { computed, onMounted, ref, watch, onUnmounted } from 'vue'
	import useUserStore from "@/store/modules/user"
	import useSetStore from '@/store/modules/set'
	import { 
		appPayConfigList,
		payUnitorder,
		appPay,
		h5Pay,
		wxPay,
		wxAppletPay,
		balancePay,
		payQuery } from "@/api/app_api/order"
	import modal from '@/plugins/modal'
	// #ifdef WEB
	import jWeixin from 'weixin-js-sdk'
	// #endif
	const userStore = useUserStore()
	const setStore = useSetStore()
	
	const props = defineProps({
		showPay: {
			type: Boolean,
			default: false
		},
		order: {
			type: Object,
			default: {}
		}
	})
	const emits = defineEmits(['close', 'success'])
	const payWayList = ref([])
	const payWayId = ref('')
	const getPayList = () => {
		appPayConfigList().then((res) => {
			// #ifdef MP-WEIXIN
			payWayList.value = res.data.filter(item => item.id === 1 || item.id === 2) || []
			// #endif
			// #ifndef MP-WEIXIN
			payWayList.value = res.data
			// #endif
		})
	}
	//选择支付方式
	const changePayWay = (e) => {
		payWayId.value = e.id
	}
	
	// 关闭支付
	const closePay = () => {
		clearTimer()
		isSubmitPay.value = false
		payTimer.value = null
		emits('close')
	}
	
	// 支付
	const isSubmitPay = ref(false)
	const submitPay = () => {
		if (!payWayId.value) return uni.$u.toast('请选择支付方式')
		if (!props.order?.orderNumber) return uni.$u.toast('订单号为空')
		isSubmitPay.value = true
		switch (payWayId.value) {
			case 1 : 
					wxPayFun(1)
				break;
			case 2 :
					balancePayFun(2)
				break;
			case 3 :
					// 微信代付
					// console.log("http://erp.tydigit.cn/h5?orderNumber=" + props.order?.orderNumber),
					uni.share({
							provider: "weixin",
							scene: "WXSceneSession",
							type: 0,
							href: "https://erp.tydigit.cn/h5?orderNumber=" + props.order?.orderNumber,
							title: "廷与食材APP-付款请求",
							summary: "我在廷与食材APP上面订了一些食材，麻烦您帮我付个款吧！",
							imageUrl: "https://erp.tydigit.cn/app_api/img/app/wxService.png",
							success: function(e) {
									console.log("success:" + JSON.stringify(e))
							},
							fail: function(e) {
									console.log("fail:" + JSON.stringify(e))
							}
					});
				break;
			case 4 :
					// 通联微信
					appPayFun(4)
				break;
			case 5 :
					// 通联支付宝
					appPayFun(5)
				break;
			case 6 :
					// 通联代付
					appPayFun(6)
				break;
			case 8 :
					// 通联微信统一下订单
					uni.login({
						provider: 'weixin',
						success: loginRes => {
							const data = loginRes.authResult;
							payUnitorder(props.order?.orderNumber, data.openid).then(res => {
								// console.log(res.data.sign)
								// #ifdef APP-PLUS
								if (res.code == 200) {
									// 获取当前app在哪个端          
									const platform = uni.getSystemInfoSync().platform;
									// 安卓端是appid，IOS端是appId，一定区分好，uniapp文档并没有说明。
									const appId = platform === 'ios' ? 'appId' : 'appid';
									const orderInfo = {
										[appId]: res.data.appid,
										noncestr: String(res.data.randomstr),
										package: "Sign=WXPay",
										partnerid: res.data.cusid,
										prepayid: res.data.reqsn,
										timestamp: res.data.fintime,
										sign: String(res.data.sign),
									};
									// console.log('发起支付参数：', orderInfo)
									uni.requestPayment({
										provider: 'wxpay',
										orderInfo: orderInfo,
										success(res) {
											// console.log('微信支付成功：', res);
											uni.$u.toast('支付成功')
											isSubmitPay.value = false
											paySuccess(paymentId, '微信支付')
											emits('close')
										},
										fail(e) {
											// console.log('微信支付失败：', e);
											uni.$u.toast('支付失败')
											isSubmitPay.value = false
										},
									});
								}
								// #endif
							})
						}
					})
				break;
		}
		// emits('confirm')
	}
	
	// 微信支付
	const wxPayFun = (paymentId) => {
		const params = {
			orderNumber: props.order.orderNumber
		}
		// #ifdef MP-WEIXIN
			// 微信小程序支付
			wxAppletPay(params).then(res => {
				// console.log({
				// 	timeStamp: res.data.timestamp.toString(),
				// 	paySign: res.data.sign,
				// 	nonceStr: res.data.noncestr,
				// 	package: `prepay_id=${res.data.prepayid}`,
				// 	signType: 'MD5'
				// })
				if (!res.data.timestamp || !res.data.sign || !res.data.noncestr || !res.data.prepayid) {
					uni.$u.toast('订单信息错误')
					isSubmitPay.value = false
					return false
				}
				uni.requestPayment({
				  provider: 'wxpay',
				  timeStamp: res.data.timestamp.toString(),
				  paySign: res.data.sign,
				  nonceStr: res.data.noncestr,
				  package: `prepay_id=${res.data.prepayid}`,
					signType: 'MD5',
					success(payRes) {
						uni.$u.toast('支付成功')
						isSubmitPay.value = false
						paySuccess(paymentId, '微信支付')
						emits('close')
					},
					fail(payErr) {
						uni.$u.toast('支付失败')
						isSubmitPay.value = false
					}
				})
			}).catch(err => {
				uni.$u.toast('支付信息错误')
				isSubmitPay.value = false
			})
		// #endif
		// #ifdef APP-PLUS
			// 微信APP支付
			wxPay(params).then(res => {
				uni.getProvider()
				const orderInfo = res.data
				orderInfo.timestamp = String(orderInfo.timestamp)
				orderInfo.package = 'Sign=WXPay'
				uni.requestPayment({
					provider: 'wxpay',
					orderInfo: orderInfo,
					// #ifdef APP-HARMONY
					orderInfo: JSON.stringify(orderInfo),
					// #endif
					success: (res) => {
						uni.$u.toast('支付成功')
						isSubmitPay.value = false
						paySuccess(paymentId, '微信支付')
						emits('close')
					},
					fail: (err) => {
						uni.$u.toast('支付失败')
						isSubmitPay.value = false
					}
				})
			}).catch(err => {
				uni.$u.toast('支付信息错误')
				isSubmitPay.value = false
			})
		// #endif
		// #ifdef WEB
			// 微信h5支付
			h5Pay(params).then(res => {
				const data = res.data
				const configData = {
					debug: false,
					appId: data.appid,
					timestamp: data.timestamp,
					nonceStr: data.noncestr,
					signature: data.sign,
					jsApiList: ['chooseWXPay']
				}
				jWeixin.config(configData)
				console.log('权限校验结束')
				jWeixin.ready(res => {
					jWeixin.checkJsApi({
						jsApiList: ['chooseWXPay'],
						success: res => {
							console.log('checkjsapi Success')
							console.log(res)
						},
						fail: err => {
							uni.$u.toast(err)
							isSubmitPay.value = false
						}
					})
					jWeixin.chooseWXPay({
						timestamp: data.timestamp,
						nonceStr: data.noncestr,
						package: 'prepay_id=' + data.prepayid,
						signType: 'MD5',
						paySign: data.sign,
						success: res => {
							uni.$u.toast('支付成功')
							isSubmitPay.value = false
							paySuccess(paymentId, '微信支付')
							emits('close')
						},
						cancel: res => {
							isSubmitPay.value = false
						},
						fail: err => {
							uni.$u.toast(err)
							isSubmitPay.value = false
						}
					})
				})
				jWeixin.error(err => {
					uni.$u.toast(err)
					isSubmitPay.value = false
				})
			}).catch(err => {
				uni.$u.toast('支付信息错误')
				isSubmitPay.value = false
			})
		// #endif
	}
	
	// 余额支付
	const balancePayFun = (paymentId) => {
		balancePay({
			id: props.order.id
		}).then(res => {
			uni.$u.toast('支付成功')
			isSubmitPay.value = false
			paySuccess(paymentId, '余额支付')
			emits('close')
		}).catch(err => {
			uni.$u.toast('支付失败')
			isSubmitPay.value = false
		})
	}
	
	// app支付
	const appPayFun = (paymentId) => {
		const params = {
			paymentId,
			orderNumber: props.order.orderNumber
		}
		appPay(params).then(res => {
			// console.log(res)
			const data = res.msg;
			// console.log('url:' + data)
			getPaySuccess(params)
			if (params.paymentId == 4) { // 通联微信
				// #ifdef APP-PLUS
				plus.share.getServices(
					res => {
						let sweixin = null;
						for (let i in res) {
							if (res[i].id == 'weixin') {
								sweixin = res[i]
							}
						}
						//唤醒微信小程序
						if (sweixin) {
							console.log('拉起通联小程序：' + data)
							sweixin.launchMiniProgram({
									id: 'gh_e64a1a89a0ad', //微信开放平台 --- 绑定的微信小程序的 --- 原始id
									type: 0, //小程序版本  0-正式版； 1-测试版； 2-体验版。
									path: data //小程序的页面,用传的参数在小程序接值判断跳转指定页面
								},
								res2 => {
									if (res2.indexOf('success') > -1) {
										uni.$u.toast('支付成功')
										isSubmitPay.value = false
										paySuccess(paymentId, '微信支付')
										emits('close')
									} else if (res2.indexOf('cancel') > -1) {
										uni.$u.toast('取消支付，请稍后重试')
										isSubmitPay.value = false
									} else if (res2.indexOf('fail') > -1) {
										uni.$u.toast('支付失败，请稍后重试')
										isSubmitPay.value = false
									} else {
										uni.$u.toast('支付成功')
										isSubmitPay.value = false
										paySuccess(paymentId, '微信支付')
										emits('close')
									}
								},
								err2 => {
									uni.$u.toast('支付失败，请稍后重试')
									isSubmitPay.value = false
									clearTimer()
									// this.clearTimer()
								});
						} else {
							console.log("未安装微信逻辑")
							uni.$u.toast('支付失败，请稍后重试')
							isSubmitPay.value = false
						}
					}
				)
				// #endif
			} else if (params.paymentId == 5) { // 通联支付宝
				// #ifdef APP-PLUS
				plus.runtime.openURL(data, err => {
					// console.log("支付宝调用返回：" + err)
					// console.log(data, err)
					uni.showToast({
						title: "打开支付宝失败！请检查是否已安装？",
						icon: 'none'
					})
				})
				// #endif
			} else if (params.paymentId == 6) { // 通联代付
				// #ifdef APP-PLUS
				plus.runtime.openURL(data) //这里默认使用外部浏览器打开而不是内部web-view组件打开
				// #endif
				// #ifdef H5
				window.open(data)
				// #endif	
			}
		}).catch(err => {
			
		})
	}
	
	
	
	// 查询是否支付
	const payTimer = ref(null)
	const getPaySuccess = (params) => {
		payTimer.value = setInterval(() => {
			payQuery({
				orderNumber: params.orderNumber
			}).then(res => {
				console.log(res)
				const data = res.data
				if (res.code === 200 && data.retcode === "SUCCESS" && parseInt(data.trxamt) > 0 && data.trxstatus ===
					'0000') {
					clearTimer()
					// #ifdef APP-PLUS
					const platform = uni.getSystemInfoSync().osName
					if (platform === 'android') {
						plus.runtime.openURL("tydigit://");
					} else {
						plus.runtime.openURL("cn.tydigit.shop");
					}
					// #endif
					if (params.paymentId === 4) {
						this.paySuccess('微信支付')
					} else if (params.paymentId === 5) {
						this.paySuccess('支付宝')
					} else if (params.paymentId === 6) {
						this.paySuccess('二维码')
					}
				}
			})
		}, 3000)
	}
	
	const clearTimer = () => {
		clearInterval(payTimer.value)
	}
	
	const paySuccess = (paymentId, name) => {
		emits('success', {
			payName: name,
			paymentId: paymentId,
			orderId: props.order?.id,
			orderNumber: props.order?.orderNumber,
			actualPrice: props.order?.actualPrice
		})
	}
	watch(() => props.showPay, (nval, oval) => {
		if (nval) {
			getPayList()
		}
	})
	onMounted(() => {
		getPayList()
	})
</script>

<style lang="scss" scoped>
  .pay-popup {
  	border-radius: 20rpx 20rpx 0rpx 0rpx;
  	background-color: #ffffff;
		&-title {
			height: 48px;
			font-size: 16px;
			font-weight: 600;
			text-align: center;
			justify-content: center;
			padding: 0 15px;
		}
		&-content {
			padding: 0 15px;
		}
		&-money {
			text-align: center;
			font-size: 28rpx;
			color: $primary-color;
			font-weight: 600;
			&-num {
				font-size: 36rpx;
			} 
		}
		&-way {
			margin-top: 40rpx;
			&-item {
				padding-top: 10px;
				&+.pay-popup-way-item {
					border-top: 1px solid $line-color;
				}
				&-icon {
					width: 80rpx;
					height: 80rpx;
					&-img {
						width: 80rpx;
						height: 80rpx;
					}
				}
				&-name {
					font-size: 28rpx;
					margin-left: 30rpx;
				}
				&-check {
					margin-left: auto;
				}
				&-no {
					display: none;
				}
			}
		}
		&-btns {
			justify-content: center;
			padding: 40rpx 0;
			&-item {
				width: 200rpx;
				height: 68rpx;
				border-radius: 34rpx;
				font-size: 28rpx;
			}
		}
  }
</style>
